//
//  CAUserInfoController.m
//  cascade-realm
//
//  Created by QSC on 24/5/24.
//

#import "CAUserInfoController.h"
#import "PGDatePickManager.h"
#import "MHD_CountryPickerView.h"

@interface CAUserInfoController ()
@property (nonatomic,strong)UIImageView * headImagev;
@property (nonatomic,strong)UILabel* nameLabel;
@property (nonatomic,strong)UILabel* DateLabel;
@property (nonatomic,strong)UIButton* CountryBtn;
@property (nonatomic,strong)UIButton* PostBtn;
@end

@implementation CAUserInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navTitle = @"Edit Profile";
    
    [self setUpView];
}


- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    [Tool colorGradientLayerForView:self.PostBtn frame:self.PostBtn.bounds colors:@[Hex(0xB3E600),Hex(0xD4E600)] locations:@[@0.0,@1.0]];
}

- (void)setUpView{
    
    UIImageView * headImgv = [UIImageView new];
    self.headImagev = headImgv;
    UIImageView * photoImgv = [[UIImageView alloc] initWithImage:Img(@"mine_photo")];
    [self.view addSubview:headImgv];
    [headImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.navView.mas_bottom).offset(73);
        make.size.mas_equalTo(100);
    }];
    [headImgv sd_setImageWithURL:[NSURL URLWithString:CAUserInfo.shared.userInfo.avatarThumbUrl] placeholderImage:Img(@"defult_head")];
    
    [self.view addSubview:photoImgv];
    [photoImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headImgv).offset(-10);
        make.bottom.equalTo(headImgv);
        make.size.mas_equalTo(25);
    }];
    headImgv.userInteractionEnabled = YES;
    headImgv.layer.cornerRadius = 50;
    headImgv.clipsToBounds = YES;
    
    [headImgv addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadImage)]];
    
    
    self.nameLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x404040) text:CAUserInfo.shared.userInfo.nickname];
    UIView *nameView = [self edittingRow:@"Nick Name" rightView:self.nameLabel];
    [self.view addSubview:nameView];
    [nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.centerX.equalTo(self.view);
        make.top.equalTo(headImgv.mas_bottom).offset(36);
        make.height.mas_equalTo(44);
    }];
    
    [nameView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeName)]];
    
    
    self.DateLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x404040) text:CAUserInfo.shared.userInfo.birthday];
    UIView *dateView = [self edittingRow:@"Date of Birth" rightView:self.DateLabel];
    [self.view addSubview:dateView];
    [dateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.centerX.equalTo(self.view);
        make.top.equalTo(nameView.mas_bottom).offset(24);
        make.height.mas_equalTo(44);
    }];
    
    [dateView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeDate)]];
    
    
    self.CountryBtn = [UIButton ButtonWithFont:Font(16) color:Hex(0x404040) text:CAUserInfo.shared.userInfo.country];
    [self.CountryBtn setImage:Img(@"mine_arrow") forState:UIControlStateNormal];
    [self.CountryBtn sizeToFit];
    [self.CountryBtn setButtonImageTitleStyle:ButtonImageTitleStyleRight padding:0];
    self.CountryBtn.userInteractionEnabled = NO;
    UIView *countryView = [self edittingRow:@"Country" rightView:self.CountryBtn];
    [self.view addSubview:countryView];
    [countryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.centerX.equalTo(self.view);
        make.top.equalTo(dateView.mas_bottom).offset(24);
        make.height.mas_equalTo(44);
    }];
    
    [countryView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeCountry)]];
    
    
    self.PostBtn = [UIButton ButtonWithFont:BoldFont(18) color:[UIColor whiteColor] text:@"Post"];
    [self.view addSubview:self.PostBtn];
    self.PostBtn.layer.cornerRadius = 22;
    self.PostBtn.clipsToBounds = true;
    [self.PostBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(countryView.mas_bottom).offset(100);
        make.left.right.height.equalTo(countryView);
    }];
    [self.PostBtn addTarget:self action:@selector(PostClick) forControlEvents:UIControlEventTouchUpInside];
}


- (UIView *)edittingRow:(NSString *)leftTitle rightView:(UIView *)rightView{
    UIView * view = [UIView new];
    view.layer.cornerRadius = 22;
    view.backgroundColor = [UIColor whiteColor];
    [view setDefultBorder];
    
    UILabel * label = [UILabel LabelWithFont:Font(16) color:[[UIColor blackColor] colorWithAlphaComponent:0.3] text:leftTitle];
    
    [view addSubview:label];
    [view addSubview:rightView];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(20);
    }];
    
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.right.equalTo(view).offset(-20);
    }];
    return  view;
}


- (void)changeHeadImage{
    WeakSelf
    [self getImageWithSelectedImageBlock:^(UIImage * _Nonnull image,NSData * data) {
      
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.png",dateString];
        
        
        [Tool ShowLoading];
        
        [Http uploadFile:data fileName:fileName  success:^(NSString * _Nonnull name) {
            [weakSelf updateHead:name];
            [Http PostLogWithPage:@"editavatar"];
        } failure:^{
            [Tool HideLoading];
        }];
    }];
}

- (void)updateHead:(NSString *)fileName
{
    WeakSelf
    [Http postWithURL:updateAvatar params:@{@"avatarPath":fileName} success:^(id  _Nonnull responseObject) {
         
        [Tool HideLoading];
        
        
        [CAUserInfo refreshUserInfo:^{
            [weakSelf.headImagev sd_setImageWithURL:[NSURL URLWithString:CAUserInfo.shared.userInfo.avatarThumbUrl] placeholderImage:Img(@"defult_head")] ;
        }];
        
    } failure:^(id  _Nonnull errObject) {
      
        [Tool HideLoading];
    }];
}


- (void)changeName{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"Edit NickName" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"Nick Name";
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action1];
   
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UITextField *textF = alert.textFields.firstObject;
        self.nameLabel.text = textF.text;
        
    }];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)changeDate{

    
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.datePickerMode = PGDatePickerModeDate;
    datePicker.maximumDate = [[NSDate date] initWithTimeIntervalSinceNow:  - 24 * 60 * 60 * 365 * 18 ] ;
    datePicker.language = @"en";
    [datePicker setDate:[NSDate dateWithString:self.DateLabel.text format:@"yyyy-MM-dd"]];
    WeakSelf
    datePicker.selectedDate = ^(NSDateComponents *dateComponents) {
   
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *date = [calendar dateFromComponents:dateComponents];
        weakSelf.DateLabel.text = [date stringWithFormat:@"yyyy-MM-dd"];
    };
    [self presentViewController:datePickManager animated:false completion:nil];
}

- (void)changeCountry{
    

    MHD_CountryPickerView * picker = [[MHD_CountryPickerView alloc] init];
    WeakSelf
    picker.confirmClickBlock = ^(NSString * _Nonnull countryName, NSString * _Nonnull countryCode) {
      
        [weakSelf.CountryBtn setTitle:countryName forState:UIControlStateNormal];
        [weakSelf.CountryBtn sizeToFit];
        [weakSelf.CountryBtn setButtonImageTitleStyle:ButtonImageTitleStyleRight padding:0];
    };
    
    picker.pickerBackgroundColor = [UIColor whiteColor];
    picker.pickerLabelColor =  Hex(0x404040);
  
    picker.cancelButtonTitle = @"cancel";
    picker.cancelButtonTitleColor = Hex(0x404040);
    picker.cancelButtonFontSize = 14.f;
    picker.confirmButtonTitle = @"ok";
    picker.confirmButtonTitleColor =  Hex(0x404040);
    picker.confirmButtonFontSize = 14.f;
    picker.centerTitle = @"";
 
    [self.view addSubview:picker];
    
    [picker showCountryPickerView];
}


- (void)PostClick{
    
    NSDictionary * dic = @{
        @"birthday":self.DateLabel.text,
        @"country":self.CountryBtn.titleLabel.text,
        @"nickname":self.nameLabel.text
    };
    
    WeakSelf
    [Http postWithURL:saveUserInfo params:dic success:^(id  _Nonnull responseObject) {
            
        
        [EasyTextView showText:@"Post Success"];
        
        [CAUserInfo refreshUserInfo:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        
    } failure:^(id  _Nonnull errObject) {
        
    }];
    
    
}

@end
